package com.hulk.dryad.web.oauth2.base.service.impl;


import cn.hutool.core.util.StrUtil;
import com.hulk.dryad.common.constant.CacheConstants;
import com.hulk.dryad.common.constant.CommonConstants;
import com.hulk.dryad.common.constant.SecurityConstants;
import com.hulk.dryad.common.constant.enums.BEC;
import com.hulk.dryad.common.exception.BaseRteException;
import com.hulk.dryad.common.util.WebUtils;
import com.hulk.dryad.manage.tenant.TenantContextHolder;
import com.hulk.dryad.manage.tenant.TenantHierarchyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @author hulk
 * @date 2020/03/25
 * <p/>
 * 扩展 JdbcClientDetailsService
 */
@Service
public class DryadClientDetailsServiceImpl extends com.hulk.dryad.web.oauth2.base.service.impl.JdbcClientDetailsService {

    @Autowired
    private CacheManager cacheManager;

    /**
     * 重写原生方法支持redis缓存
     *
     * @param clientId
     * @return ClientDetails
     * @throws InvalidClientException
     */
    @Override
    public ClientDetails loadClientByClientId(String clientId) {
		String tenantId = TenantHierarchyUtil.getTenantId();
        if (StrUtil.isBlank(tenantId)) {
            throw new BaseRteException(BEC.E_1005);
        }
        ClientDetails clientDetails;
        //get from cache
        Cache cache = cacheManager.getCache(tenantId + StrUtil.COLON + CacheConstants.CLIENT_DETAILS_KEY);
        clientDetails = cache.get(clientId, ClientDetails.class);
        if (null != clientDetails) {
            return clientDetails;
        }
        //get from db
        super.setSelectClientDetailsSql(String.format(SecurityConstants.DEFAULT_SELECT_STATEMENT));
        clientDetails = super.loadClientByClientId(clientId);
        if (null != clientDetails) {
            cache.putIfAbsent(clientId, clientDetails);
        }
        return clientDetails;
    }


}
